local skynet = require "skynet"
local s = require "service"
local CMD = require "game_cmd"


s.client = {}
s.resp.client = function(source, fd, cmd, msg)
    if s.client[cmd] then
        local ret_msg, ret_cmd_id = s.client[cmd](fd, msg, source)
        skynet.send(source, "lua", "send_by_fd", fd, ret_msg, ret_cmd_id)
    else
        skynet.error("s.resp.client fail", cmd)
    end
end

s.client.login = function(fd, msg, source)
    local username = msg.username
    local pw = msg.pwd
    local gate = source
    local node = skynet.getenv("node")
    local ret_cmd_id = CMD.SERVER_LOGIN

    local retLoginMsg = {
        cmd = "login",
        status = 1,
        msg = "登陆成功",
        id = -1
    }

    -- 校验用户名密码
    local isok, userinfo = skynet.call("mysql_node", "lua", "query_player_info", username, pw)
    skynet.error("login call mysql:", isok, userinfo)
    if not isok then
        retLoginMsg.status = -1
        retLoginMsg.msg = "密码错误"
        return retLoginMsg, ret_cmd_id
    end

    local playerid = userinfo.id
    -- 发给agentmgr
    local isok, agent = skynet.call("agentmgr", "lua", "reqlogin", playerid, node, gate)
    if not isok then
        retLoginMsg.status = -1
        retLoginMsg.msg = "请求mgr失败"
        return retLoginMsg, ret_cmd_id
    end
    -- 回应gate
    skynet.error("login, agent:", agent)
    local isok = skynet.call(gate, "lua", "sure_agent", fd, playerid, agent)
    if not isok then
        retLoginMsg.status = -1
        retLoginMsg.msg = "gate注册失败"
        return retLoginMsg, ret_cmd_id
    end

    retLoginMsg.id = playerid
    skynet.error("login succ " .. playerid)
    return retLoginMsg, ret_cmd_id
end

s.start(...)
